package com.youlai.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.system.common.result.Result;
import com.youlai.system.mapper.OrderItemMapper;
import com.youlai.system.mapper.ProductMapper;
import com.youlai.system.model.entity.Product;
import com.youlai.system.model.pojo.PieStatsInfo;
import com.youlai.system.model.pojo.ProductStatsInfo;
import com.youlai.system.model.vo.ProductStatsVO;
import com.youlai.system.service.ProductStatsService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

import static com.youlai.system.common.constant.Constants.*;

/**
 * ClassName: ProductStatsServiceImpl
 * Package: com.youlai.system.service.impl
 * Description:
 *
 * @Author LIEX
 * @create 2024/3/11 14:15
 * @Version 1.0
 */
@Service
public class ProductStatsServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductStatsService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    OrderItemMapper orderItemMapper;
    @Override
    public Result<ProductStatsVO> getProductStats() {
        //获取日期
        LocalDate localDate = LocalDate.now();
        //当日商品浏览量KEY
        String PVKey = Product_VISITED_STATS+localDate;
        //当日浏览人数KEY
        String UVKey = PEOPLE_VISITED_STATS+localDate;
        /*
        * 商品日访问量
        *
        * */
        String productV=stringRedisTemplate.opsForValue().get(PVKey);
        int productNum=0;
        if(productV!=null&& !productV.isEmpty()){
            productNum=Integer.parseInt(productV);
        }

        /*
         * 商店浏览人数(日)
         *
         * */
        Long peopleV = stringRedisTemplate.opsForHyperLogLog().size(UVKey);
        Integer peopleNum=peopleV.intValue();

        /*
         * 商店浏览人数(月)
         *
         * */
        int mUV= 0;
        Set<String> peopleVKeys = stringRedisTemplate.keys(PEOPLE_VISITED_STATS+"*");
        if(peopleVKeys!=null&&!peopleVKeys.isEmpty()){
            List<String> keys = new ArrayList<>(peopleVKeys);
            for (String key : keys) {
                int num = stringRedisTemplate.opsForHyperLogLog().size(key).intValue();
                mUV += num;
            }
        }

        //返回VO
        ProductStatsVO productStatsVO =new ProductStatsVO();
        productStatsVO.setPV(productNum);
        productStatsVO.setMUV(mUV);
        productStatsVO.setUV(peopleNum);

        /*
        * 饼图与柱状图
        * */
        Set<String> uvKeys = stringRedisTemplate.keys(UV_PRODUCT_STATS_PREFIX +"*");
        Set<String> cateGoryKeys = stringRedisTemplate.keys(PRODUCT_CATEGORY_STATS_PREFIX+"*");
        if (uvKeys!=null&&!uvKeys.isEmpty() && cateGoryKeys!=null && !cateGoryKeys.isEmpty()) {
            List<ProductStatsInfo> productStatsInfoList=new ArrayList<>();
            /*
            * 柱状图处理： 遍历每个key，获取每个商品对应的数据：
            *           pv，uv，收藏量，销售量
            * */
            uvKeys.forEach(key ->{
                //封装某个商品的数据
                ProductStatsInfo productStatsInfo=new ProductStatsInfo();
               // uv ， pv 获取
                Integer uvNum = stringRedisTemplate.opsForHyperLogLog().size(key).intValue();
                Integer pvNum = Integer.parseInt(Objects.requireNonNull(stringRedisTemplate.opsForValue().get("pv" + key.substring(2))));
                //收藏量 获取
                int collectNum = 0;
                if (stringRedisTemplate.opsForSet().size("collect" + key.substring(2))!=null){
                collectNum = Objects.requireNonNull(stringRedisTemplate.opsForSet().size("collect" + key.substring(2))).intValue();
                }

                //查询商品
                String productId = key.substring(key.lastIndexOf(":")+1);
                Product product= getById(Integer.parseInt(productId));
                if(product!=null){
                    //查询销售量
                   Integer saleNum = orderItemMapper.getProductSaleNum(product.getId());
                    if (product.getTitle().length()>14){
                        productStatsInfo.setProductName(product.getTitle().substring(0,14));
                    }else {
                        productStatsInfo.setProductName(product.getTitle());
                    }
                    productStatsInfo.setCollect(collectNum);
                    productStatsInfo.setUvNum(uvNum);
                    productStatsInfo.setSaleNum(saleNum==null?0:saleNum);
                    productStatsInfo.setPvNum(pvNum);
                    productStatsInfoList.add(productStatsInfo);
                }

            });
            //降序排序
            Collections.sort(productStatsInfoList);
            //排序结果放入VO中
            productStatsInfoList.forEach(productStatsInfo -> {
                 productStatsVO.getBarCollectYAxis().add(productStatsInfo.getCollect());
                 productStatsVO.getBarSaleNumYAxis().add(productStatsInfo.getSaleNum());
                 productStatsVO.getBarPVYAxis().add(productStatsInfo.getPvNum());
                 productStatsVO.getBarUVYAxis().add(productStatsInfo.getUvNum());
                 productStatsVO.getBarXAxis().add(productStatsInfo.getProductName());
            });
            /*
             * 饼图处理：变量key，获取每个类别的访问量
             * */
            cateGoryKeys.forEach(cateGoryKey->{
                int num;
                String numStr = stringRedisTemplate.opsForValue().get(cateGoryKey);
                if(numStr!=null){
                    //访问量
                    num=Integer.parseInt(numStr);
                    //分类名称
                    String name = cateGoryKey.substring(cateGoryKey.lastIndexOf(":")+1);
                    productStatsVO.getPieStatsInfos().add(new PieStatsInfo(name,num));
                }
            });
            // redis中有数据
            return Result.success(productStatsVO);
        }else {
            //redis中无数据
            return Result.success(productStatsVO);
        }

    }
}
